<template>
	<view class="tech-orders">
		<!-- 筛选栏 -->
		<view class="filter-bar">
			<picker 
				:range="statusOptions" 
				range-key="name"
				:value="statusIndex"
				@change="onStatusChange"
			>
				<view class="filter-item">
					<text>{{ statusOptions[statusIndex].name }}</text>
					<text class="arrow">▼</text>
				</view>
			</picker>
		</view>
		
		<!-- 订单列表 -->
		<scroll-view 
			class="order-scroll" 
			scroll-y 
			@scrolltolower="loadMore"
			refresher-enabled 
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<view class="order-item" v-for="order in orderList" :key="order.id" @click="goOrderDetail(order.id)">
				<view class="order-header">
					<text class="order-title">{{ order.title }}</text>
					<text class="order-status" :class="getStatusClass(order.status)">
						{{ getStatusText(order.status) }}
					</text>
				</view>
				
				<view class="order-content">
					<text class="order-desc">{{ order.description }}</text>
				</view>
				
				<view class="order-info">
					<view class="info-row">
						<text class="label">预算：</text>
						<text class="value budget">￥{{ order.budget }}</text>
					</view>
					<view class="info-row">
						<text class="label">分类：</text>
						<text class="value">{{ order.categoryName }}</text>
					</view>
					<view class="info-row">
						<text class="label">发布者：</text>
						<text class="value">{{ order.userName }}</text>
					</view>
					<view class="info-row">
						<text class="label">截止时间：</text>
						<text class="value">{{ formatTime(order.deadline) }}</text>
					</view>
				</view>
				
				<!-- 技术员操作 -->
				<view class="tech-actions">
					<button 
						class="action-btn accept" 
						v-if="order.status === 1 && !order.techId"
						@click.stop="acceptOrder(order.id)"
					>
						接单
					</button>
					
					<button 
						class="action-btn complete" 
						v-if="order.status === 2 && order.techId === currentUserId"
						@click.stop="completeOrder(order.id)"
					>
						标记完成
					</button>
					
					<button 
						class="action-btn progress" 
						v-if="order.status === 2 && order.techId === currentUserId"
						@click.stop="updateProgress(order.id)"
					>
						更新进度
					</button>
				</view>
			</view>
			
			<view class="load-more" v-if="hasMore">
				<text v-if="loading">加载中...</text>
				<text v-else>上拉加载更多</text>
			</view>
			
			<view class="no-more" v-if="!hasMore && orderList.length > 0">
				<text>没有更多数据了</text>
			</view>
			
			<view class="empty" v-if="!loading && orderList.length === 0">
				<text>暂无订单数据</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				orderList: [],
				loading: false,
				refreshing: false,
				hasMore: true,
				pageNum: 1,
				pageSize: 10,
				statusIndex: 0,
				statusOptions: [
					{ name: '全部订单', value: '' },
					{ name: '可接订单', value: 1 },
					{ name: '进行中', value: 2 },
					{ name: '待验收', value: 3 },
					{ name: '已完成', value: 4 }
				],
				currentUserId: null
			}
		},
		onLoad(options) {
			this.checkPermission()
			this.currentUserId = this.$store.state.user.id
			
			// 如果有传入状态参数，设置默认筛选
			if (options.status) {
				const index = this.statusOptions.findIndex(item => item.value == options.status)
				if (index > -1) {
					this.statusIndex = index
				}
			}
			
			this.loadOrders()
		},
		methods: {
			checkPermission() {
				if (!this.$store || !this.$store.getters.isTech) {
					uni.showToast({
						title: '权限不足',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
					return false
				}
				return true
			},
			
			async loadOrders(refresh = false) {
				if (this.loading) return
				
				this.loading = true
				
				if (refresh) {
					this.pageNum = 1
					this.hasMore = true
				}
				
				try {
					const params = {
						pageNum: this.pageNum,
						pageSize: this.pageSize
					}
					
					// 根据状态筛选
					if (this.statusOptions[this.statusIndex].value) {
						params.status = this.statusOptions[this.statusIndex].value
					}
					
					// 如果是查看可接订单，只显示未指派的
					if (params.status === 1) {
						params.available = true
					}
					
					// 如果不是可接订单，只显示自己相关的订单
					if (params.status !== 1) {
						params.techId = this.currentUserId
					}
					
					const res = await this.$api.getOrderList(params)
					
					if (res.code === 200) {
						const newOrders = res.data || []
						
						if (refresh) {
							this.orderList = newOrders
						} else {
							this.orderList = [...this.orderList, ...newOrders]
						}
						
						this.hasMore = newOrders.length === this.pageSize
						this.pageNum++
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '加载失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
					this.refreshing = false
				}
			},
			
			onRefresh() {
				this.refreshing = true
				this.loadOrders(true)
			},
			
			loadMore() {
				if (this.hasMore && !this.loading) {
					this.loadOrders()
				}
			},
			
			onStatusChange(e) {
				this.statusIndex = e.detail.value
				this.loadOrders(true)
			},
			
			goOrderDetail(id) {
				uni.navigateTo({
					url: `/pages/order/detail?id=${id}`
				})
			},
			
			async acceptOrder(id) {
				uni.showModal({
					title: '确认接单',
					content: '确定要接受此订单吗？接单后请按时完成。',
					success: async (res) => {
						if (res.confirm) {
							try {
								await this.$api.acceptOrder(id)
								uni.showToast({
									title: '接单成功',
									icon: 'success'
								})
								this.loadOrders(true)
							} catch (error) {
								uni.showToast({
									title: error.message || '接单失败',
									icon: 'none'
								})
							}
						}
					}
				})
			},
			
			async completeOrder(id) {
				uni.showModal({
					title: '确认完成',
					content: '确定要标记此订单为完成状态吗？',
					success: async (res) => {
						if (res.confirm) {
							try {
								await this.$api.completeOrder(id)
								uni.showToast({
									title: '标记成功',
									icon: 'success'
								})
								this.loadOrders(true)
							} catch (error) {
								uni.showToast({
									title: error.message || '操作失败',
									icon: 'none'
								})
							}
						}
					}
				})
			},
			
			updateProgress(id) {
				uni.navigateTo({
					url: `/pages/tech/progress?orderId=${id}`
				})
			},
			
			getStatusClass(status) {
				const statusMap = {
					1: 'status-pending',
					2: 'status-processing',
					3: 'status-reviewing',
					4: 'status-completed',
					5: 'status-cancelled'
				}
				return statusMap[status] || ''
			},
			
			getStatusText(status) {
				const statusMap = {
					1: '待接单',
					2: '进行中',
					3: '待验收',
					4: '已完成',
					5: '已取消'
				}
				return statusMap[status] || '未知'
			},
			
			formatTime(time) {
				if (!time) return ''
				const date = new Date(time)
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
			}
		}
	}
</script>

<style lang="scss" scoped>
	.tech-orders {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background: #f5f5f5;
	}
	
	.filter-bar {
		background: #fff;
		padding: 20rpx;
		border-bottom: 1rpx solid #eee;
		display: flex;
		flex-wrap: wrap;
		gap: 10rpx;
		
		.filter-item {
			flex: 1;
			min-width: 150rpx;
			padding: 20rpx;
			background: #f8f8f8;
			border-radius: 10rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 28rpx;
			
			.arrow {
				color: #999;
				font-size: 20rpx;
			}
		}
	}
	
	.order-scroll {
		flex: 1;
		padding: 20rpx;
	}
	
	.order-item {
		background: #fff;
		border-radius: 15rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		
		.order-header {
			display: flex;
			justify-content: space-between;
			align-items: flex-start;
			margin-bottom: 20rpx;
			
			.order-title {
				flex: 1;
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
				margin-right: 20rpx;
				line-height: 1.4;
			}
			
			.order-status {
				font-size: 24rpx;
				padding: 6rpx 16rpx;
				border-radius: 15rpx;
				white-space: nowrap;
			}
		}
		
		.order-content {
			margin-bottom: 20rpx;
			
			.order-desc {
				font-size: 28rpx;
				color: #666;
				line-height: 1.5;
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				overflow: hidden;
			}
		}
		
		.order-info {
			margin-bottom: 20rpx;
			
			.info-row {
				display: flex;
				margin-bottom: 10rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				.label {
					font-size: 24rpx;
					color: #666;
					width: 120rpx;
				}
				
				.value {
					flex: 1;
					font-size: 24rpx;
					color: #333;
					
					&.budget {
						font-weight: bold;
						color: #FF6B6B;
					}
				}
			}
		}
		
		.tech-actions {
			display: flex;
			gap: 20rpx;
			
			.action-btn {
				flex: 1;
				height: 60rpx;
				border: none;
				border-radius: 30rpx;
				font-size: 24rpx;
				
				&.accept {
					background: #007bff;
					color: #fff;
				}
				
				&.complete {
					background: #28a745;
					color: #fff;
				}
				
				&.progress {
					background: #ffc107;
					color: #333;
				}
			}
		}
	}
	
	.load-more, .no-more {
		text-align: center;
		padding: 40rpx 0;
		color: #999;
		font-size: 28rpx;
	}
	
	.empty {
		text-align: center;
		padding: 200rpx 0;
		color: #999;
		font-size: 28rpx;
	}
	
	// 状态样式
	.status-pending {
		background: rgba(255, 149, 0, 0.1);
		color: #ff9500;
	}
	
	.status-processing {
		background: rgba(0, 122, 255, 0.1);
		color: #007AFF;
	}
	
	.status-reviewing {
		background: rgba(88, 86, 214, 0.1);
		color: #5856d6;
	}
	
	.status-completed {
		background: rgba(52, 199, 89, 0.1);
		color: #34c759;
	}
	
	.status-cancelled {
		background: rgba(255, 59, 48, 0.1);
		color: #ff3b30;
	}
</style>